package com.yyoa.util;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.ArrayUtils;

import com.google.common.collect.Lists;
import com.yyoa.model.Constraint;
import com.yyoa.model.ConstraintGroup;

@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class Constraints {

	public static Constraint mergeConstraintByAnd(Constraint... constraints) {
		if (ArrayUtils.isEmpty(constraints)) {
			return null;
		}
		return mergeConstraintByAnd(asList(constraints));
	}

	public static Constraint mergeConstraintByAnd(List<Constraint> constraints) {
		filter(constraints);
		if (CollectionUtils.isEmpty(constraints)) {
			return null;
		}
		if (constraints.size() == 1) {
			return constraints.get(0);
		}
		return new ConstraintGroup(ConstraintGroup.LOGIC_AND, constraints);
	}

	public static Constraint mergeConstraintByOr(Constraint... constraints) {
		if (ArrayUtils.isEmpty(constraints)) {
			return null;
		}

		return mergeConstraintByOr(asList(constraints));
	}

	public static Constraint mergeConstraintByOr(List<Constraint> constraints) {
		filter(constraints);
		if (CollectionUtils.isEmpty(constraints)) {
			return null;
		}
		if (constraints.size() == 1) {
			return constraints.get(0);
		}
		return new ConstraintGroup(ConstraintGroup.LOGIC_OR, constraints);
	}

	private static List asList(Constraint... constraints) {
		List constraintList = Lists.newArrayList();
		for (Constraint constraint : constraints) {
			constraintList.add(constraint);
		}
		return constraintList;
	}

	private static void filter(List<Constraint> constraints) {
		CollectionUtils.filter(constraints, new Predicate() {
			public boolean evaluate(Object object) {
				if (object == null) {
					return false;
				}
				return true;
			}
		});
	}

}